import { useState } from "react";

function Square({ value, onSquareClick }) {
    return <button className="square" onClick={onSquareClick}>{value}</button>
}

export default function Board() {
    const [sq, setSq] = useState(Array(9).fill(null));
    const [isX, setIsX] = useState(true);
    const handleClick = (i) => {
        if (sq[i]) {
            return;
        }
        const nextSq = sq.slice();
        if (isX) {
            nextSq[i] = 'X';
        } else {
            nextSq[i] = 'O';
        }
        setSq(nextSq);
        setIsX(!isX);
    }
    // 
    return (
        <>
            <div className="board-row">
                <Square value={sq[0]} onSquareClick={() => handleClick(0)} />
                <Square value={sq[1]} onSquareClick={() => handleClick(1)} />
                <Square value={sq[2]} onSquareClick={() => handleClick(2)} />
            </div>
            <div className="board-row">
                <Square value={sq[3]} onSquareClick={() => handleClick(3)} />
                <Square value={sq[4]} onSquareClick={() => handleClick(4)} />
                <Square value={sq[5]} onSquareClick={() => handleClick(5)} />
            </div>
            <div className="board-row">
                <Square value={sq[6]} onSquareClick={() => handleClick(6)} />
                <Square value={sq[7]} onSquareClick={() => handleClick(7)} />
                <Square value={sq[8]} onSquareClick={() => handleClick(8)} />
            </div>
        </>
    )
}

function calculateWinner(square) {
    const lines = [
        [0, 1, 2], // 第一行
        [3, 4, 5], // 第二行
        [6, 7, 8], // 第三行
        [0, 3, 6], // 第一列
        [1, 4, 7], // 第二列
        [2, 5, 8], // 第三列
        [0, 4, 8], // 左上到右下对角线
        [2, 4, 6]  // 右上到左下对角线
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (square[a] && square[a] === square[b] && square[a] === square[c]) { // 以 && 为分隔，首先判断是否为空，然后判断是否相等
            return square[a];
        }
    }
    return null;
}

 